import React, {Component} from 'react';
import {LIMIT} from "../../../config";
import {
    reqResources,
    reqAddResource,
    reqDeleteResource,
    reqUpdateResource,
    reqResourcesByTitle
} from "../../../api";
import {formatDate} from "../../../util";
import {
    Card, Table, Tag, Typography, Space,
    Modal, Form, Input,
    Button, Popconfirm, message
} from "antd";
import {PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';

const {Link} = Typography;

class Resources extends Component {

    state = {
        resources: [],
        current: 1,
        total: 0,
        isEdit: false,
        isModalVisible: false,
        resourceId: 0,
    }

    formRef = React.createRef();

    componentDidMount() {
        this.initResources();
    }

    initResources = async () => {
        let {current} = this.state;
        let {data} = await reqResources(current);
        let {list, total} = data;
        this.setState({resources: list, total});
    }

    editResource = (data) => {
        this.setState({isEdit: true, isModalVisible: true, resourceId: data.id});
        this.formRef.current.setFieldsValue(data);
    }

    deleteResource = async (data) => {
        let {status, msg} = await reqDeleteResource(data.id);
        if (status === 0) {
            message.success(msg);
            this.initResources();
            return;
        }
        message.error("网络异常");
    }

    handleOk = () => {
        let {isEdit} = this.state;
        isEdit ? this.updateResource() : this.addResource();
    }

    updateResource = () => {
        let {resourceId} = this.state;
        this.commitForm((resource) => {
            resource.id = resourceId;
            return reqUpdateResource(resource);
        })
    }

    addResource = () => {
        this.commitForm(reqAddResource)
    }

    commitForm = (func) => {
        this.formRef.current.validateFields().then(async value => {
            let {status, msg} = await func(value);
            if (status === 0) {
                message.success(msg);
                this.handleCancel();
                this.initResources();
                return;
            }
            message.error("网络异常");
            this.handleCancel();
        }).catch(() => {
            message.error("输入数据有误");
        })
    }

    handleCancel = () => {
        this.formRef.current.resetFields()
        this.setState({isModalVisible: false})
    }

    pageChange = (current) => {
        this.setState({current}, () => {
            this.initResources();
        })
    }

    search = async (e) => {
        if (e.target.value.trim()) {
            let {data} = await reqResourcesByTitle(e.target.value);
            this.setState({resources: data});
            return;
        }
        this.initResources();
    }

    columns = [
        {
            title: '资源',
            dataIndex: 'title',
            render: (data) => {
                return (<Tag color="geekblue">{data}</Tag>)
            }
        },
        {
            title: '链接',
            dataIndex: 'url',
            render: (data) => {
                return <Link href={data} target="_blank">{data}</Link>
            }
        },
        {
            title: '提取码',
            dataIndex: 'token',
            render: (data) => {
                return <Tag color="green">{data}</Tag>
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: (data) => {
                return formatDate("YYYY-MM-dd HH:mm:ss", data)
            }
        },
        {
            title: '操作',
            render: (data) => {
                return (
                    <Space size="small">
                        <Button size="small"
                                icon={<EditOutlined/>}
                                onClick={() => this.editResource(data)}/>
                        <Popconfirm
                            title="确定删除吗？"
                            onConfirm={() => this.deleteResource(data)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button size="small" icon={<DeleteOutlined/>} danger/>
                        </Popconfirm>
                    </Space>
                )
            }
        },
    ];

    render() {
        let {resources, isModalVisible, isEdit, current, total} = this.state;
        return (
            <Card title={<Input
                style={{width: 270}}
                placeholder="输入标题关键字，回车搜索"
                onPressEnter={this.search}/>}
                  extra={<Button type="primary"
                                 onClick={() => this.setState({isModalVisible: true, isEdit: false})}
                                 icon={<PlusOutlined/>}>添加资源</Button>}>
                <Table
                    size="small"
                    rowKey="id"
                    pagination={{current, total, defaultPageSize: LIMIT,
                        showTotal: (total) => `共 ${total} 个资源`,
                        onChange: this.pageChange}}
                    dataSource={resources}
                    columns={this.columns}/>
                <Modal title={isEdit ? "编辑资源" : "添加资源"}
                       forceRender={true}
                       visible={isModalVisible}
                       onOk={this.handleOk}
                       onCancel={this.handleCancel}>
                    <Form
                        name="basic"
                        ref={this.formRef}
                    >
                        <Form.Item
                            name="title"
                            rules={[
                                {required: true, message: '请输入资源名称!'}
                            ]}
                        >
                            <Input placeholder="请输入资源名称"/>
                        </Form.Item>
                        <Form.Item
                            name="url"
                            rules={[
                                {required: true, message: '请输入资源链接!'},
                            ]}
                        >
                            <Input placeholder="请输入资源链接"/>
                        </Form.Item>
                        <Form.Item
                            name="token"
                            rules={[
                                {required: true, message: '请输入资源提取码!'}
                            ]}
                        >
                            <Input placeholder="请输入资源提取码"/>
                        </Form.Item>
                    </Form>
                </Modal>
            </Card>
        );
    }
}

export default Resources;
